package com.example.shop_2207.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.shop_2207.R
import com.example.shop_2207.adapter.CarAdapter
import com.example.shop_2207.database.MyDbUtils
import com.example.shop_2207.databinding.FragmentCarBinding
import com.example.shop_2207.entity.CarEntity
import com.example.shop_2207.mvvm.BaseFragment


class CarFragment : BaseFragment<FragmentCarBinding, CarViewModel>() {
    val list = mutableListOf<CarEntity>()
    lateinit var carAdapter: CarAdapter
    override fun getLayout(): Int = R.layout.fragment_car

    override fun getViewModel(): Class<CarViewModel> = CarViewModel::class.java

    override fun initView() {
        carAdapter = CarAdapter(list)
        binding.rvCar.adapter = carAdapter
        binding.rvCar.layoutManager = LinearLayoutManager(context)
        viewModel.selectCar()
        //显示合计金额
        total()
        /* //显示全选 是选中状态还是未选中状态
         checkAll()*/
        //给全选添加监听
        binding.cbCheckall.setOnCheckedChangeListener { buttonView, isChecked ->
            //点击全选控件时
            binding.cbCheckall.setOnClickListener {
                list.forEach {
                    it.isCheck = isChecked
                }
                carAdapter.notifyDataSetChanged()
                //但全选按钮变化变化时，合计金额也要发生变化
                total()
            }
        }
        carAdapter.addChildClickViewIds(R.id.cb, R.id.iv_less, R.id.iv_add, R.id.iv_delete)
        carAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.cb -> {
                    //更新list集合中的值
                    list[position].isCheck = !list[position].isCheck
                    //更新页面上的值
                    (carAdapter.getViewByPosition(position, R.id.cb) as CheckBox).isChecked =
                        list[position].isCheck
                }
                R.id.iv_less -> {
                    if(list[position].count==1){
                        viewModel.deleteCar(list[position].id.toString())
                        list.removeAt(position)
                        carAdapter.notifyItemRemoved(position)
                    }else{
                        //调用后台请求
                        viewModel.addCar(-1, list[position].goods_id)
                        list[position].count += -1
                        (carAdapter.getViewByPosition(position, R.id.tv_num) as TextView).text =
                            "${list[position].count}"
                        (carAdapter.getViewByPosition(position, R.id.tv_total) as TextView).text =
                            "合计：${list[position].goods_default_price * list[position].count}元"
                    }
                }
                R.id.iv_add -> {
                    //调用后台请求
                    viewModel.addCar(1, list[position].goods_id)
                    list[position].count += 1
                    (carAdapter.getViewByPosition(position, R.id.tv_num) as TextView).text =
                        "${list[position].count}"
                    (carAdapter.getViewByPosition(position, R.id.tv_total) as TextView).text =
                        "合计：${list[position].goods_default_price * list[position].count}元"
                }
                R.id.iv_delete -> {
                    viewModel.deleteCar(list[position].id.toString())
                    //list集合删除
                    list.removeAt(position)
                    //局部刷新，只移除这个item就行
                    carAdapter.notifyItemRemoved(position)
                }
            }
            //无论item点击了任何地方，下方内容都要刷新
            checkAll()
            total()
        }
        //点击支付按钮事件
        binding.toPay.setOnClickListener {
            val checklist = mutableListOf<Boolean>()//用来判断是否有选中的item
            var ids:StringBuffer = StringBuffer()//用来删除选中的item
            list.forEach {
                checklist.add(it.isCheck)
            }
            if(true in checklist){
                //有选中的item能够去支付、、生成新的订单---删除购物车的数据
                list.forEach {
                    if(it.isCheck){
                        it.order_status = 0//待结算的订单
                        MyDbUtils.getDb().getOrderDao().insertOrder(it)
                        if(ids.length>0){
                            ids.append(",")
                        }
                        ids.append(it.id)
                    }
                }
                viewModel.deleteCar(ids.toString())

                ARouter.getInstance().build("/app/PayActivity").navigation()
            }else{
                ToastUtils.showLong("请最少选择一种商品去结算")
            }

        }
    }

    private fun checkAll() {
        //用来存放所有item的选中状态
        val flaglist = mutableListOf<Boolean>()
        list.forEach {
            flaglist.add(it.isCheck)
        }
        //false !in flaglist  当集合中都为true是，返回值为true  当存在false时，返回值为false
        binding.cbCheckall.isChecked = false !in flaglist
    }

    private fun total() {
        var money = 0
        list.forEach {
            if (it.isCheck) {
                money += it.goods_default_price * it.count
            }
        }
        binding.tvTotalall.text = "合计:$money 元"
    }

    override fun initData() {
        viewModel.selectSuccess.observe(this) {
            ToastUtils.showLong(it.message)
            if (it.code == 200) {
                list.clear()
                list.addAll(it.data)
                carAdapter.notifyDataSetChanged()
            }
        }
        viewModel.selectFail.observe(this) {
            ToastUtils.showLong(it)
        }
        viewModel.addSuccess.observe(this) {
            ToastUtils.showLong(it.message)
        }
        viewModel.addFail.observe(this) {
            ToastUtils.showLong(it)
        }
        viewModel.deleteSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.deleteFail.observe(this){
            ToastUtils.showLong(it)
        }
    }
}